//
// Created by bobin on 18-6-7.
//

#include "dpptam/ua_detrac_loader.h"


void load_ua_detrac(const std::string path,
                    const std::string train_path, const std::string sequence,
                    std::vector<std::vector<bbox>> &box_set,
                    std::vector<std::string> &image_files) {
    std::vector<bbox> bboxes;
    using std::string;
    using std::ifstream;
    using std::stringstream;
    ifstream ifs;
    ifs.open(path.c_str(), std::ios_base::in);
    while (!ifs.eof()) {
        string s;
        getline(ifs, s);

        if (s.find(sequence) == string::npos) {
            continue;
        }
        stringstream ss;
        int stt = sequence.size();
        ss << s.substr(stt);
        bbox box;
        double x = -1;
        double y = -1;
        double w = -1;
        double h = -1;
        ss >> box.ImageID >> box.ObjectID
           >> box.ObjectClass >> x >> y >> w >> h;

        box.left = floor(x);
        box.top = floor(y);
        box.width = ceil(w);
        box.height = ceil(h);
        bboxes.push_back(box);
    }

    std::set<int> im_id_set;
    unsigned num_images = 0;
//        LOG(INFO) << bboxes.size() << std::endl;
    for (unsigned i = 0; i < bboxes.size(); ++i) {
        bbox box = bboxes[i];

        im_id_set.insert((box.ImageID));
        if (num_images < box.ImageID) {
            num_images = box.ImageID;
        }
    }

    box_set = std::vector<std::vector<bbox>>(num_images,
                                             std::vector<bbox>());

    for (auto &box : bboxes) {
        int im_id = box.ImageID;
        box_set[im_id - 1].push_back(box);
    }


    image_files.resize(num_images);
    for (auto id : im_id_set) {
        std::stringstream ss;
        ss << train_path << "/img" << std::setfill('0')
           << std::setw(5) << id << ".jpg";
        image_files[id - 1] = ss.str();
    }
}


void load_ua_detrac_seq(const std::string path, std::vector<std::string> &seq_vec) {
    std::vector<bbox> bboxes;
    using std::string;
    using std::ifstream;
    using std::stringstream;
    ifstream ifs;
    ifs.open(path.c_str(), std::ios_base::in);
    std::set<string> seq_set;
    while (!ifs.eof()) {
        string s;
        getline(ifs, s);
        std::string sequence;
        stringstream ss;
        ss << s;
        ss >> sequence;
        seq_set.insert(sequence);
    }
    seq_vec = std::vector<std::string>(seq_set.begin(), seq_set.end());
}
